<template>
  <div class="new-prediction-overview">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>AI智能预测中心</h1>
      <p>基于机器学习的电力负荷智能预测系统，支持多模型分析</p>
    </div>

    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="page-title">
          <Icon type="ios-pulse" />
          短期电力负荷预测
        </h2>
        <div class="subtitle">根据截止前一天历史数据，预测24小时的电力负荷</div>
      </div>
      <div class="toolbar-right">
        <div class="status-indicator" :class="{ 'online': systemStatus.online }">
          <span class="status-dot"></span>
          <span class="status-text">{{ systemStatus.text }}</span>
        </div>
        <Button type="primary" size="small" @click="refreshData" class="refresh-btn">
          <Icon type="ios-refresh" />
          刷新数据
        </Button>
      </div>
    </div>

    <!-- 核心预测区域 -->
    <div class="prediction-workspace">
      <!-- 预测配置面板 -->
      <div class="config-panel">
        <Card>
          <div slot="title">
            <Icon type="ios-settings" />
            预测配置
          </div>
          
          <div class="config-form">
            <!-- 模型选择 -->
            <div class="form-row">
              <label class="form-label">预测模型</label>
              <Select v-model="config.model" placeholder="选择AI模型" size="large">
                <Option value="lightgbm" label="LightGBM">
                  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                    <span><Icon type="ios-flash" /> LightGBM</span>
                    <span style="color: #4ecdc4; font-size: 12px;">高性能</span>
                  </div>
                </Option>
                <Option value="xgboost" label="XGBoost">
                  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                    <span><Icon type="ios-thunderstorm" /> XGBoost</span>
                    <span style="color: #75deef; font-size: 12px;">高精度</span>
                  </div>
                </Option>
                <Option value="ensemble" label="智能集成">
                  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                    <span><Icon type="ios-git-network" /> 智能集成</span>
                    <span style="color: #faad14; font-size: 12px;">推荐</span>
                  </div>
                </Option>
              </Select>
            </div>

            <!-- 预测模式 -->
            <div class="form-row">
              <label class="form-label">预测模式</label>
              <RadioGroup v-model="config.mode">
                <Radio label="single">单模型预测</Radio>
                <Radio label="multiple">多模型对比</Radio>
              </RadioGroup>
            </div>

            <!-- 操作按钮 -->
            <div class="action-row">
              <Button type="primary" size="large" long @click="startPrediction" :loading="loading">
                <Icon type="ios-rocket" />
                {{ loading ? '预测中...' : '开始AI预测' }}
              </Button>
            </div>

            <!-- 当天气象信息 -->
            <div class="weather-info-section">
              <div class="weather-header">
                <Icon type="ios-cloud" />
                <span>预测日气象信息</span>
              </div>
              <div class="weather-grid">
                <div class="weather-item" v-for="item in weatherItems" :key="item.key">
                  <div class="weather-icon">
                    <Icon :type="item.icon" :color="item.color" />
                  </div>
                  <div class="weather-content">
                    <div class="weather-value">{{ item.value }}</div>
                    <div class="weather-label">{{ item.label }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      <!-- 预测结果展示 -->
      <div class="results-panel">
        <!-- 实时指标 - 多模型对比时不显示 -->
        <div class="metrics-grid" v-if="config.mode !== 'multiple'">
          <div class="metric-card" v-for="metric in currentMetrics" :key="metric.key">
            <div class="metric-icon" :class="metric.iconClass">
              <Icon :type="metric.icon" />
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ metric.value }}</div>
              <div class="metric-label">{{ metric.label }}</div>
              <div class="metric-trend" :class="{ 'up': metric.trend > 0, 'down': metric.trend < 0 }">
                <Icon :type="metric.trend > 0 ? 'ios-arrow-up' : 'ios-arrow-down'" />
                {{ Math.abs(metric.trend) }}%
              </div>
            </div>
          </div>
        </div>

        <!-- 负荷曲线图 -->
        <Card class="chart-card">
          <div slot="title">
            <Icon type="ios-analytics" />
            24小时负荷预测曲线
            <div class="chart-controls">
              <Button 
                type="success" 
                size="small" 
                @click="exportChartData"
                :loading="exportLoading"
                class="export-btn"
              >
                <Icon type="ios-download" />
                导出图表数据
              </Button>
            </div>
          </div>
          
          <div class="chart-container" ref="loadChart" v-if="predictionData.length > 0 || Object.keys(multiModelData).length > 0"></div>
          <div v-show="predictionData.length === 0 && Object.keys(multiModelData).length === 0" class="chart-placeholder">
            <Icon type="ios-analytics" size="48" />
            <p>暂无预测数据，请先进行预测</p>
          </div>
        </Card>
      </div>
    </div>

    <!-- 详细分析区域 -->
    <div class="analysis-section" v-if="predictionData.length > 0">
      <div class="analysis-grid">
        <!-- 特征重要性分析 -->
        <div class="analysis-card">
          <div class="card-header">
            <Icon type="ios-pie" />
            <h3>特征重要性分析</h3>
          </div>
          <div class="importance-charts">
            <FeatureImportanceComparison :featureData="featureImportanceData" />
            <ModelWeightAndCategoryChart :featureData="featureImportanceData" />
          </div>
        </div>
        
        <!-- 模型性能指标 - 已禁用 -->
        <!-- <div class="analysis-card">
          <div class="card-header">
            <Icon type="ios-analytics" />
            <h3>模型性能指标</h3>
          </div>
          <div class="performance-summary">
            <h4>性能指标评估</h4>
            <div class="performance-factor" v-for="metric in performanceMetrics" :key="metric.name">
              <div class="factor-name">{{ metric.name }}</div>
              <div class="factor-impact" :class="metric.level">
                <span>{{ metric.level === 'excellent' ? '优秀' : metric.level === 'good' ? '良好' : '一般' }}</span>
                <span class="impact-score">{{ metric.score }}%</span>
              </div>
              <Progress :percent="metric.score" :stroke-color="getProgressColor(metric.score)" :show-text="false" />
            </div>
          </div>
        </div> -->
        
        <!-- 气象影响分析 - 已禁用 -->
        <!-- <div class="analysis-card">
          <div class="card-header">
            <Icon type="ios-cloud" />
            <h3>气象影响分析</h3>
          </div>
          <div class="weather-impact-chart" ref="weatherChart"></div>
        </div> -->
      </div>
    </div>

  </div>
</template>

<script>
import { Card, Select, Option, DatePicker, RadioGroup, Radio, Button, ButtonGroup, Icon, Tabs, TabPane, Table, Progress } from 'view-design'
import * as echarts from 'echarts'
import { predictionAPI, realTimePredictionAPI } from '@/utils/api'
import { 
  getCurrentUTCDate, 
  prepareDateForAPI, 
  getUTCTimezoneInfo,
  getDatePickerOptions,
  isValidDateFormat
} from '@/utils/timezone'
import PredictionSummary from './PredictionSummary'
import FeatureImportanceComparison from './FeatureImportanceComparison'
import ModelWeightAndCategoryChart from './ModelWeightAndCategoryChart'

export default {
  name: 'NewPredictionOverview',
  components: {
    Card, Select, Option, DatePicker, RadioGroup, Radio, Button, ButtonGroup, Icon, Tabs, TabPane, Table, Progress, PredictionSummary,
    FeatureImportanceComparison,
    ModelWeightAndCategoryChart
  },
  data() {
    return {
      loading: false,
      activeTab: 'importance',
      exportLoading: false,
      
      // 系统状态
      systemStatus: {
        online: true,
        text: '系统正常'
      },
      
      // 预测配置 - 使用UTC日期字符串
      config: {
        target_date: getCurrentUTCDate(), // 使用UTC日期字符串
        model: 'ensemble',
        mode: 'single' // single: 单模型预测, multi: 多模型对比
      },
      
      // 当前UTC时间信息
      utcInfo: {
        current_time: '',
        timezone: 'UTC',
        timezone_offset: 0
      },
      
      // 可选日期列表（当前开始7天）
      availableDates: [],
      
      // 预测数据
      predictionData: [],
      multiModelData: {}, // 多模型预测数据 {modelName: [values]}
      currentMetrics: [],
      
      // 特征重要性数据
      featureImportanceData: [],
      
      // 气象信息
      weatherInfo: null,
      
      // 性能指标 - 动态计算，不使用固定值
      performanceMetrics: [],
      
      // 特征重要性洞察 - 动态计算，不使用固定值
      importanceInsights: [],
      
      // 图表实例管理
      loadChart: null,
      importanceChart: null,
      weatherChart: null,
      
      // 预测历史
      predictionHistory: [],
      historyColumns: [
        {
          title: 'ID',
          key: 'id',
          width: 80
        },
        {
          title: '日期',
          key: 'dt',
          width: 120
        },
        {
          title: '预测值',
          key: 'predVal',
          width: 100
        },
        {
          title: '时间戳',
          key: 'dtm',
          width: 180
        },
        {
          title: '模型',
          key: 'model',
          width: 100
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 180
        }
      ],
      
      // 使用统一的UTC日期选择器配置
      datePickerOptions: getDatePickerOptions()
    }
  },
  mounted() {
    console.log('AI智能预测中心页面加载完成')
    
    // 初始化指标显示
    this.loadCurrentMetrics()
    
    // 更新UTC时间信息
    this.updateUTCInfo()
    
    // 加载可选日期列表
    this.loadAvailableDates()
    
    // 加载预测历史
    this.loadPredictionHistory()
    
          // 延迟初始化图表，确保DOM完全渲染
      this.$nextTick(() => {
        setTimeout(() => {
          console.log('开始初始化图表')
          this.initLoadChart()
          this.initImportanceChart()
          // this.initWeatherChart() // 气象影响分析已禁用
        }, 300)
      })
    
    // 调试模型选择
    console.log('初始模型配置:', this.config.model)
    this.$nextTick(() => {
      console.log('DOM更新后模型配置:', this.config.model)
    })
  },
  watch: {
    // 监听模型选择变化
    'config.model'(newModel, oldModel) {
      console.log(`模型选择变化: ${oldModel} -> ${newModel}`)
      if (this.predictionData.length > 0) {
        this.$nextTick(() => {
          this.updateLoadChart()
        })
      }
    }
  },
  
  computed: {
    // 气象信息展示项
    weatherItems() {
      return [
        {
          key: 'temp_max',
          label: '最高温度',
          value: `${this.weatherInfo?.t_max || '--'}°C`,
          icon: 'ios-thermometer',
          color: '#ff6b6b'
        },
        {
          key: 'temp_min',
          label: '最低温度',
          value: `${this.weatherInfo?.t_min || '--'}°C`,
          icon: 'ios-thermometer-outline',
          color: '#4ecdc4'
        },
        {
          key: 'humidity',
          label: '湿度',
          value: `${this.weatherInfo?.humidity || '--'}%`,
          icon: 'ios-water',
          color: '#45b7d1'
        },
        {
          key: 'precipitation',
          label: '降水量',
          value: `${this.weatherInfo?.precip || '--'}mm`,
          icon: 'ios-rainy',
          color: '#96ceb4'
        },
        // {
        //   key: 'pressure',
        //   label: '气压',
        //   value: `${this.weatherInfo?.pressure || '--'}hPa`,
        //   icon: 'ios-speedometer',
        //   color: '#feca57'
        // },
        // {
        //   key: 'wind_speed',
        //   label: '风速',
        //   value: `${this.weatherInfo?.wind_speed || '--'}m/s`,
        //   icon: 'ios-wind',
        //   color: '#ff9ff3'
        // }
      ]
    }
  },
  
  methods: {
    // 使用统一的UTC日期获取函数
    getCurrentUTCDate,
    
    // 组件销毁时清理图表实例
    beforeDestroy() {
      if (this.loadChart) {
        this.loadChart.dispose()
        this.loadChart = null
      }
      if (this.importanceChart) {
        this.importanceChart.dispose()
        this.importanceChart = null
      }
      if (this.weatherChart) {
        this.weatherChart.dispose()
        this.weatherChart = null
      }
    },
    
    // 更新UTC时间信息
    updateUTCInfo() {
      try {
        this.utcInfo = getUTCTimezoneInfo()
        console.log('UTC时间信息更新:', this.utcInfo)
      } catch (error) {
        console.error('获取UTC时间信息失败:', error)
        // 设置默认UTC时间信息
        const now = new Date()
        this.utcInfo = {
          current_time: now.toISOString(),
          timezone: 'UTC+0',
          timezone_offset: 0
        }
      }
    },
    
    // 加载可选日期列表
    async loadAvailableDates() {
      try {
        // 直接生成从今天起往后7天的日期，不依赖API
        this.generateDefaultDates()
        console.log('✅ 加载可选日期成功:', this.availableDates)
      } catch (error) {
        console.error('❌ 加载可选日期失败:', error)
        // 生成默认的7天日期
        this.generateDefaultDates()
      }
    },
    
    // 生成默认日期列表
    generateDefaultDates() {
      const dates = []
      const today = new Date()
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(today)
        date.setUTCDate(today.getUTCDate() + i)
        
        const year = date.getUTCFullYear()
        const month = String(date.getUTCMonth() + 1).padStart(2, '0')
        const day = String(date.getUTCDate()).padStart(2, '0')
        
        dates.push({
          date: `${year}-${month}-${day}`,
          display_name: i === 0 ? '今天' : `未来第${i}天`,
          weekday: date.toLocaleDateString('zh-CN', { weekday: 'long' }),
          formatted: `${year}年${month}月${day}日`,
          utc_timestamp: Math.floor(date.getTime() / 1000),
          timezone: 'UTC'
        })
      }
      
      this.availableDates = dates
    },
    
    // 初始化图表
    initializeCharts() {
      this.$nextTick(() => {
        this.initLoadChart()
        this.initImportanceChart()
        // this.initWeatherChart() // 气象影响分析已禁用
      })
    },
    
    // 负荷预测图表
    initLoadChart(retryCount = 0) {
      if (!this.$refs.loadChart) {
        console.log('图表初始化失败：找不到图表容器')
        return
      }
      
      // 检查是否已经初始化
      if (this.loadChart) {
        console.log('图表已存在，跳过初始化')
        return
      }
      
      // 确保容器有高度，最多重试5次
      const container = this.$refs.loadChart
      if (container.offsetHeight === 0 && retryCount < 5) {
        console.log(`容器高度为0，延迟初始化 (重试 ${retryCount + 1}/5)`)
        setTimeout(() => {
          this.initLoadChart(retryCount + 1)
        }, 500)
        return
      }
      
      if (retryCount >= 5) {
        console.error('图表容器高度始终为0，强制初始化')
      }
      
      console.log('开始初始化负荷图表，容器尺寸:', container.offsetWidth, 'x', container.offsetHeight)
      
      const chart = echarts.init(this.$refs.loadChart)
      this.loadChart = chart
      
      // 不显示默认数据，只初始化空图表
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: '24小时负荷预测曲线',
          textStyle: {
            color: '#fff',
            fontSize: 16
          },
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(7, 19, 50, 0.9)',
          borderColor: '#1a3c58',
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLine: {
            lineStyle: {
              color: '#1a3c58'
            }
          },
          axisLabel: {
            color: '#999'
          }
        },
        yAxis: {
          type: 'value',
          name: '负荷(MW)',
          nameTextStyle: {
            color: '#999'
          },
          axisLine: {
            lineStyle: {
              color: '#1a3c58'
            }
          },
          axisLabel: {
            color: '#999'
          },
          splitLine: {
            lineStyle: {
              color: '#1a3c58'
            }
          }
        },
        series: []
      }
      
      chart.setOption(option)
      
      // 确保图表正确适应容器大小
      setTimeout(() => {
        chart.resize()
        console.log('初始化空图表已resize，容器尺寸:', chart.getDom().offsetWidth, 'x', chart.getDom().offsetHeight)
      }, 100)
      
      window.addEventListener('resize', () => chart.resize())
    },
    
    // 特征重要性图表
    initImportanceChart() {
      if (!this.$refs.importanceChart) return
      
      // 检查是否已经初始化
      if (this.importanceChart) {
        this.importanceChart.dispose()
      }
      
      const chart = echarts.init(this.$refs.importanceChart)
      this.importanceChart = chart
      
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: '特征重要性分析',
          textStyle: {
            color: '#fff',
            fontSize: 13
          },
          left: 'center',
          top: 18
        },
                tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0,0,0,0.8)',
          borderColor: '#1890ff',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'center',
          textStyle: {
            color: '#fff',
            fontSize: 12
          },
          itemGap: 8
        },
        series: [{
          name: '特征重要性',
          type: 'pie',
          radius: ['25%', '50%'],
          center: ['50%', '55%'],
          data: [
            { value: 96.4, name: '历史负荷', itemStyle: { color: '#1890ff' } },
            { value: 3.6, name: '气象因素', itemStyle: { color: '#52c41a' } },
            { value: 0.1, name: '时间特征', itemStyle: { color: '#faad14' } }
          ],
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{d}%',
            fontSize: 12,
            color: '#fff',
            fontWeight: 'bold'
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10,
            lineStyle: {
              color: '#fff',
              width: 1
            }
          }
        }]
      }
      
      chart.setOption(option)
    },
    
    // 更新特征重要性图表
    updateImportanceChart(featureImportanceData) {
      if (!this.$refs.importanceChart || !featureImportanceData) return
      
      const chart = echarts.init(this.$refs.importanceChart)
      
      // 解析特征重要性数据
      const featureImportance = featureImportanceData.feature_importance || {}
      const chartData = []
      
      // 转换API数据为图表数据
      if (featureImportance.temp_max) {
        chartData.push({ value: featureImportance.temp_max, name: '最高温度', itemStyle: { color: '#ff4d4f' } })
      }
      if (featureImportance.temp_min) {
        chartData.push({ value: featureImportance.temp_min, name: '最低温度', itemStyle: { color: '#1890ff' } })
      }
      if (featureImportance.weather_temp_max) {
        chartData.push({ value: featureImportance.weather_temp_max, name: '新格式最高温度', itemStyle: { color: '#52c41a' } })
      }
      if (featureImportance.weather_temp_min) {
        chartData.push({ value: featureImportance.weather_temp_min, name: '新格式最低温度', itemStyle: { color: '#13c2c2' } })
      }
      if (featureImportance.humidity) {
        chartData.push({ value: featureImportance.humidity, name: '湿度', itemStyle: { color: '#faad14' } })
      }
      
      // 如果没有数据，显示空状态
      if (chartData.length === 0) {
        console.warn('没有特征重要性数据，显示空状态')
        chartData.push(
          { value: 100, name: '暂无数据', itemStyle: { color: '#999' } }
        )
      }
      
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: '特征重要性分析',
          textStyle: {
            color: '#fff',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0,0,0,0.8)',
          borderColor: '#1890ff',
          textStyle: {
            color: '#fff'
          }
        },
        series: [{
          name: '特征重要性',
          type: 'pie',
          radius: ['30%', '55%'],
          center: ['50%', '55%'],
          data: chartData,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{d}%',
            fontSize: 12,
            color: '#fff',
            fontWeight: 'bold'
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10,
            lineStyle: {
              color: '#fff',
              width: 1
            }
          }
        }]
      }
      
      chart.setOption(option)
    },
    

    
    // 日期变化处理
    onDateChange(date) {
      console.log('日期选择变化:', date)
      // 确保日期格式为UTC字符串
      if (date) {
        const utcDate = prepareDateForAPI(date)
        console.log('转换后的UTC日期:', utcDate)
        this.config.target_date = utcDate
      }
    },
    
    // 开始预测
    async startPrediction() {
      this.loading = true
      try {
        // 直接使用配置中的UTC日期字符串
        const targetDate = this.config.target_date
        if (!targetDate || !isValidDateFormat(targetDate)) {
          this.$Message.error('请选择有效的预测日期')
          this.loading = false
          return
        }
        
        console.log('发送预测请求，目标日期:', targetDate)
        
        let response
        if (this.config.mode === 'multiple') {
          // 多模型并行预测
          response = await predictionAPI.getMultiModelPrediction({
            target_date: targetDate
          })
        } else {
          // 单模型预测
          response = await predictionAPI.getSingleDayPrediction({
            target_date: targetDate,
            model: this.config.model
          })
        }
        
        if (response.success) {
          console.log('API响应数据:', response)
          
          // 设置气象信息
          if (response.weather_info) {
            this.weatherInfo = response.weather_info
            console.log('气象信息:', this.weatherInfo)
          }
          
          if (this.config.mode === 'multiple') {
            // 多模型预测数据处理
            this.multiModelData = response.multi_model_results || {}
            this.predictionData = [] // 清空单模型数据
            
            console.log('多模型数据:', this.multiModelData)
            
            // 验证多模型数据的完整性
            let validModels = 0
            for (const [modelName, modelData] of Object.entries(this.multiModelData)) {
              if (Array.isArray(modelData) && modelData.length === 96) {
                validModels++
                console.log(`模型 ${modelName} 数据有效: ${modelData.length} 个数据点`)
              } else {
                console.warn(`模型 ${modelName} 数据无效:`, modelData)
              }
            }
            
            if (validModels === 0) {
              console.error('没有有效的多模型预测数据')
              this.$Message.error('多模型预测数据无效')
              return
            }
            
            // 多模型对比时不显示统计框
            this.currentMetrics = []
            
            this.$Message.success(`多模型预测完成！获得 ${validModels} 个有效模型的预测结果`)
          } else {
            // 单模型预测数据处理
            const predictionResult = response.prediction_results && response.prediction_results[0]
            this.predictionData = predictionResult ? predictionResult.prediction_values : this.generateMockPredictionData()
            this.multiModelData = {} // 清空多模型数据
            
            // 更新指标
            if (predictionResult) {
              this.updateCurrentMetrics({ 
                prediction_results: [{
                  avgLoad: predictionResult.avgLoad,
                  maxLoad: predictionResult.maxLoad,
                  minLoad: predictionResult.minLoad,
                  loadVariation: predictionResult.loadVariation
                }]
              })
            } else {
              this.updateCurrentMetrics({ prediction_results: [this.calculatePredictionStats()] })
            }
            
            this.$Message.success(`预测完成！模型：${this.config.model}`)
          }
          
          this.addToPredictionHistory({ 
            target_date: this.config.target_date,
            model: this.config.mode === 'multiple' ? '多模型对比' : this.config.model,
            statistics: {}
          })
          
          // 动态计算性能指标和特征重要性
          this.performanceMetrics = this.calculatePerformanceMetrics()
          
          // 更新特征重要性数据
          if (response.feature_importance_data) {
            this.featureImportanceData = response.feature_importance_data
          } else if (response.feature_importance_analysis && response.feature_importance_analysis.feature_importance_data) {
            this.featureImportanceData = response.feature_importance_analysis.feature_importance_data
          }
          
          // 更新图表
          this.$nextTick(() => {
            console.log('开始更新图表，多模型数据:', Object.keys(this.multiModelData).length)
            this.updateLoadChart()
            
            // 初始化分析图表
            setTimeout(() => {
              this.initImportanceChart()
              // this.initWeatherChart() // 气象影响分析已禁用
            }, 100)
          })
        } else {
          this.$Message.error('预测失败：' + (response.error || '未知错误'))
        }
      } catch (error) {
        console.error('预测请求错误:', error)
        this.$Message.error('预测请求失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    // 更新当前指标
    updateCurrentMetrics(data) {
      console.log('更新指标数据:', data)
      if (data.prediction_results && data.prediction_results.length > 0) {
        const result = data.prediction_results[0]
        console.log('指标结果:', result)
        this.currentMetrics = [
          {
            key: 'avg',
            icon: 'ios-analytics',
            iconClass: 'metric-blue',
            value: result.avgLoad ? `${result.avgLoad.toFixed(2)} MW` : '--',
            label: '平均负荷',
            trend: 2.3
          },
          {
            key: 'max',
            icon: 'ios-trending-up',
            iconClass: 'metric-red',
            value: result.maxLoad ? `${result.maxLoad.toFixed(2)} MW` : '--',
            label: '峰值负荷',
            trend: 1.8
          },
          {
            key: 'min',
            icon: 'ios-trending-down',
            iconClass: 'metric-green',
            value: result.minLoad ? `${result.minLoad.toFixed(2)} MW` : '--',
            label: '谷值负荷',
            trend: -0.5
          },

        ]
      } else {
        // 如果没有数据，保持默认的--显示
        this.loadCurrentMetrics()
      }
    },
    
    // 加载当前指标（默认数据）
    loadCurrentMetrics() {
      this.currentMetrics = [
        {
          key: 'avg',
          icon: 'ios-analytics',
          iconClass: 'metric-blue',
          value: '--',
          label: '平均负荷',
          trend: 0
        },
        {
          key: 'max',
          icon: 'ios-trending-up', 
          iconClass: 'metric-red',
          value: '--',
          label: '峰值负荷',
          trend: 0
        },
        {
          key: 'min',
          icon: 'ios-trending-down',
          iconClass: 'metric-green', 
          value: '--',
          label: '谷值负荷',
          trend: 0
        },

      ]
    },
    
    
    // 添加到预测历史
    addToPredictionHistory(data) {
      this.predictionHistory.unshift({
        predictTime: new Date().toLocaleString(),
        target_date: this.config.target_date,
        model: this.config.model,
        accuracy: '90.5%'
      })
    },
    
    // 刷新数据
    refreshData() {
      this.$Message.info('数据已刷新')
      this.loadCurrentMetrics()
      this.loadPredictionHistory()
    },
    
    // 加载预测历史记录 - 显示从今天起往后7天预测过的记录
    async loadPredictionHistory() {
      try {
        const response = await realTimePredictionAPI.getPredictionHistory(7)
        console.log('预测历史API响应:', response)
        
        if (response.success && response.data) {
          // 过滤只显示今天及以后的预测记录
          const today = new Date()
          const todayStr = today.toISOString().split('T')[0]
          
          // 检查数据格式，兼容两种不同的API响应格式
          this.predictionHistory = response.data
            .filter(record => {
              // 兼容两种日期字段：dt 或 target_date
              const recordDate = record.dt || record.target_date
              return recordDate >= todayStr
            })
            .map((record, index) => ({
              id: record.id || index + 1,
              dt: record.dt || record.target_date,
              predVal: record.pred_val ? `${record.pred_val} MW` : 
                      record.avg_load ? `${record.avg_load.toFixed(2)} MW` : '-- MW',
              dtm: record.dtm || record.predict_time,
              model: record.model || '未知',
              created_at: record.created_at || record.predict_time,
              // 添加额外的统计信息用于显示
              accuracy: record.accuracy || '90.5%',
              peak_load: record.peak_load,
              valley_load: record.valley_load,
              data_points: record.data_points
            }))
            .sort((a, b) => new Date(b.dt) - new Date(a.dt)) // 按日期倒序排列
          
          console.log('处理后的预测历史数据:', this.predictionHistory)
        } else {
          // 生成从今天起7天的示例预测历史
          const today = new Date()
          this.predictionHistory = []
          
          for (let i = 0; i < 7; i++) {
            const date = new Date(today)
            date.setDate(today.getDate() + i)
            const dateStr = date.toISOString().split('T')[0]
            
            // 模拟已预测的记录（前3天）
            if (i < 3) {
              this.predictionHistory.push({
                id: i + 1,
                dt: dateStr,
                predVal: `${(8000 + Math.random() * 1000).toFixed(0)} MW`,
                dtm: `${dateStr} ${14 + i}:30:00`,
                model: ['ensemble', 'xgboost', 'lightgbm'][i % 3],
                created_at: `${dateStr} ${14 + i}:30:15`,
                accuracy: '90.5%',
                peak_load: 9500 + Math.random() * 500,
                valley_load: 6500 + Math.random() * 500,
                data_points: 96
              })
            }
          }
        }
      } catch (error) {
        console.error('加载预测历史失败:', error)
        // 设置空数据
        this.predictionHistory = []
      }
    },
    
    // 获取进度条颜色
    getProgressColor(score) {
      if (score >= 80) return '#4ecdc4'
      if (score >= 60) return '#75deef'
      if (score >= 40) return '#faad14'
      return '#ff4d4f'
    },
    

    
    // 加载历史预测
    loadHistoryPrediction(row) {
      this.$Message.info('加载历史预测：' + row.target_date)
    },
    
    // 对比分析
    compareWithCurrent(row) {
      this.$Message.info('对比分析：' + row.target_date)
    },
    
    // 测试模型选择
    testModelSelection() {
      console.log('当前选中模型:', this.config.model)
      this.$Message.info('当前选中模型: ' + this.config.model)
    },
    
    // 生成模拟预测数据 - 已禁用，改为返回空数组
    generateMockPredictionData() {
      console.warn('模拟数据生成已禁用，请确保API返回真实数据')
      return []
    },
    
    // 获取不同模型的变化特性 - 已禁用
    getModelVariation(timeIndex) {
      console.warn('模型变化特性已禁用，使用真实API数据')
      return 0
    },
    
    // 从数据计算预测统计
    calculatePredictionStatsFromData(data) {
      if (!data || data.length === 0) {
        return {
          avgLoad: 0,
          maxLoad: 0,
          minLoad: 0,
          loadVariation: 0
        }
      }
      
      const values = data.map(val => parseFloat(val) || 0)
      const avgLoad = values.reduce((sum, val) => sum + val, 0) / values.length
      const maxLoad = Math.max(...values)
      const minLoad = Math.min(...values)
      const loadVariation = ((maxLoad - minLoad) / avgLoad) * 100
      
      return {
        avgLoad: avgLoad,
        maxLoad: maxLoad,
        minLoad: minLoad,
        loadVariation: loadVariation
      }
    },
    
    // 计算预测统计
    calculatePredictionStats() {
      if (!this.predictionData || this.predictionData.length === 0) {
        console.warn('没有预测数据，返回默认值')
        return {
          avgLoad: 0,
          maxLoad: 0,
          minLoad: 0,
          loadVariation: 0
        }
      }
      
      const values = this.predictionData.map(val => parseFloat(val) || 0)
      const avgLoad = values.reduce((sum, val) => sum + val, 0) / values.length
      const maxLoad = Math.max(...values)
      const minLoad = Math.min(...values)
      const loadVariation = ((maxLoad - minLoad) / avgLoad) * 100
      
      return {
        avgLoad: avgLoad,
        maxLoad: maxLoad,
        minLoad: minLoad,
        loadVariation: loadVariation
      }
    },
    
    // 动态计算性能指标
    calculatePerformanceMetrics() {
      if (!this.predictionData || this.predictionData.length === 0) {
        console.warn('没有预测数据，无法计算性能指标')
        return []
      }
      
      // 这里应该从API获取真实的性能指标
      // 暂时返回空数组，等待API提供真实数据
      return []
    },
    
    // 动态计算特征重要性洞察
    updateImportanceInsights(importanceData) {
      if (!importanceData || importanceData.length === 0) {
        this.importanceInsights = []
        return
      }
      
      this.importanceInsights = importanceData.map(item => ({
        key: item.name,
        icon: this.getImportanceIcon(item.name),
        color: this.getImportanceColor(item.name),
        text: `${item.name}的重要性为${item.value}%`
      }))
    },
    
    // 动态计算气象影响 - 已禁用
    // calculateWeatherImpact() {
    //   if (!this.weatherInfo) {
    //     console.warn('没有气象数据，返回默认影响值')
    //     return [0, 0, 0, 0, 0, 0]
    //   }
    //   
    //   // 基于实际气象数据计算影响值
    //   const tMax = this.weatherInfo.t_max || 25
    //   const tMin = this.weatherInfo.t_min || 15
    //   const humidity = this.weatherInfo.humidity || 60
    //   const precip = this.weatherInfo.precip || 0
    //   const windSpeed = this.weatherInfo.wind_speed || 3
    //   
    //   // 计算影响评分（0-100）
    //   const tempImpact = Math.min(100, Math.max(0, (tMax - 10) * 2)) // 温度影响
    //   const humidityImpact = Math.min(100, Math.max(0, humidity * 0.8)) // 湿度影响
    //   const precipImpact = Math.min(100, Math.max(0, precip * 5)) // 降水影响
    //   const windImpact = Math.min(100, Math.max(0, windSpeed * 10)) // 风速影响
    //   
    //   return [
    //     Math.round(tempImpact), // 最高温度
    //     Math.round(tempImpact * 0.8), // 最低温度
    //     Math.round((tempImpact + tempImpact * 0.8) / 2), // 平均温度
    //     Math.round(humidityImpact), // 湿度
    //     Math.round(precipImpact), // 降水量
    //     Math.round(windImpact) // 风速
    //   ]
    // },
    
    // 获取特征重要性图标
    getImportanceIcon(featureName) {
      const iconMap = {
        '最高温度': 'ios-thermometer',
        '最低温度': 'ios-thermometer-outline',
        '平均温度': 'ios-thermometer',
        '湿度': 'ios-water',
        '降水量': 'ios-rainy',
        '风速': 'ios-wind',
        '历史负荷': 'ios-trending-up',
        '气象因素': 'ios-cloud',
        '时间特征': 'ios-time'
      }
      return iconMap[featureName] || 'ios-analytics'
    },
    
    // 获取特征重要性颜色
    getImportanceColor(featureName) {
      const colorMap = {
        '最高温度': '#ff4d4f',
        '最低温度': '#1890ff',
        '平均温度': '#52c41a',
        '湿度': '#faad14',
        '降水量': '#722ed1',
        '风速': '#13c2c2',
        '历史负荷': '#1890ff',
        '气象因素': '#52c41a',
        '时间特征': '#faad14'
      }
      return colorMap[featureName] || '#999'
    },
    
    // 更新负荷图表
    updateLoadChart(retryCount = 0) {
      if (!this.$refs.loadChart) {
        console.log('图表更新失败：找不到图表容器')
        return
      }
      
      // 确保容器有正确的尺寸，最多重试5次
      const container = this.$refs.loadChart
      if ((container.offsetWidth === 0 || container.offsetHeight === 0) && retryCount < 5) {
        console.log(`容器尺寸为0，延迟更新图表... (重试 ${retryCount + 1}/5)`)
        setTimeout(() => {
          this.updateLoadChart(retryCount + 1)
        }, 500)
        return
      }
      
      if (retryCount >= 5) {
        console.error('图表容器尺寸始终为0，放弃初始化')
        return
      }
      
      // 检查是否有数据
      const hasMultiData = Object.keys(this.multiModelData).length > 0
      const hasSingleData = this.predictionData && this.predictionData.length > 0
      
      if (!hasMultiData && !hasSingleData) {
        console.log('图表更新失败：没有可用数据')
        return
      }
      
      console.log('开始更新负荷图表，多模型数据:', hasMultiData, '单模型数据:', hasSingleData)
      console.log('多模型数据详情:', this.multiModelData)
      console.log('当前配置模式:', this.config.mode)
      
      // 获取或创建图表实例
      let chart = this.loadChart
      if (!chart) {
        console.log('创建新的图表实例')
        chart = echarts.init(this.$refs.loadChart)
        this.loadChart = chart
      }
      
      // 准备系列数据和Y轴范围计算
      let allValues = []
      let seriesData = []
      
      if (hasMultiData) {
        // 多模型数据处理
        const modelColors = {
          'lightgbm': '#4ecdc4',
          'xgboost': '#75deef', 
          'ensemble': '#faad14'
        }
        
        Object.keys(this.multiModelData).forEach(modelName => {
          const modelData = this.multiModelData[modelName]
          if (modelData && modelData.length > 0) {
            const cleanedData = this.cleanPredictionData(modelData)
            allValues = allValues.concat(cleanedData)
            
            seriesData.push({
              name: modelName.toUpperCase(),
              type: 'line',
              data: cleanedData,
              smooth: true,
              lineStyle: {
                color: modelColors[modelName] || '#999',
                width: 3
              },
              itemStyle: {
                color: modelColors[modelName] || '#999'
              },
              symbol: 'circle',
              symbolSize: 6,
              showSymbol: false,
              emphasis: {
                focus: 'series'
              }
            })
          }
        })
      } else {
        // 单模型数据处理
        const cleanedData = this.cleanPredictionData(this.predictionData)
        allValues = cleanedData
        
        seriesData.push({
          name: '预测负荷',
          type: 'line',
          data: cleanedData,
          smooth: true,
          lineStyle: {
            color: this.getModelColor(),
            width: 3
          },
          itemStyle: {
            color: this.getModelColor()
          },
          symbol: 'circle',
          symbolSize: 6,
          showSymbol: false
        })
      }
      
      // 计算数据范围，动态调整Y轴
      const minValue = Math.min(...allValues)
      const maxValue = Math.max(...allValues)
      const range = maxValue - minValue
      const padding = range * 0.1 // 上下各留10%的边距
      const yAxisMin = Math.max(0, minValue - padding)
      const yAxisMax = maxValue + padding
      
      // 生成24小时时间标签（每15分钟一个点，共96个点）
      const timeLabels = []
      for (let i = 0; i < 96; i++) {
        const hour = Math.floor(i / 4)
        const minute = (i % 4) * 15
        const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
        timeLabels.push(timeStr)
      }
      
      const option = {
          backgroundColor: 'transparent',
          title: {
            text: hasMultiData ? '多模型24小时负荷预测对比' : `${this.config.model ? this.config.model.toUpperCase() : 'AI'} 24小时负荷预测`,
            textStyle: {
              color: '#fff',
              fontSize: 16
            },
            left: 'center',
            top: 10
          },
          legend: hasMultiData ? {
            data: seriesData.map(s => s.name),
            textStyle: {
              color: '#8cc8ff'
            },
            top: 40,
            right: '10%'
          } : undefined,
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(7, 19, 50, 0.9)',
            borderColor: '#1a3c58',
            textStyle: {
              color: '#fff'
            },
            formatter: function(params) {
              let result = params[0].axisValue + '<br/>'
              params.forEach(param => {
                result += `${param.marker}${param.seriesName}: ${param.value.toFixed(2)} MW<br/>`
              })
              return result
            }
          },
          grid: {
            left: '3%',
            right: hasMultiData ? '20%' : '3%',
            bottom: '8%',
            top: hasMultiData ? '15%' : '12%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: timeLabels,
            axisLine: {
              lineStyle: {
                color: '#1a3c58'
              }
            },
            axisLabel: {
              color: '#999',
              rotate: 45,
              interval: 3,
              formatter: function(value, index) {
                // 只显示整点时间
                if (index % 4 === 0) {
                  return value
                }
                return ''
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '负荷(MW)',
            min: yAxisMin,
            max: yAxisMax,
            nameTextStyle: {
              color: '#999'
            },
            axisLine: {
              lineStyle: {
                color: '#1a3c58'
              }
            },
            axisLabel: {
              color: '#999',
              formatter: function(value) {
                return value.toFixed(0)
              }
            },
            splitLine: {
              lineStyle: {
                color: '#1a3c58'
              }
            }
          },
          series: seriesData
        }
      
      chart.setOption(option, true)
      
      console.log('✅ 图表更新完成，系列数量:', seriesData.length)
      if (hasMultiData) {
        console.log('多模型系列:', seriesData.map(s => ({ name: s.name, dataLength: s.data.length })))
      }
      
      // 确保图表正确适应容器大小
      setTimeout(() => {
        chart.resize()
        console.log('更新图表已resize，容器尺寸:', chart.getDom().offsetWidth, 'x', chart.getDom().offsetHeight)
        console.log('图表更新完成，当前配置:', {
          hasMultiData,
          seriesCount: seriesData.length,
          yAxisRange: `${yAxisMin.toFixed(0)} - ${yAxisMax.toFixed(0)}`
        })
      }, 100)
    },
    
    // 数据清理方法
    cleanPredictionData(data) {
      return data.map(val => {
        const numVal = parseFloat(val)
        if (isNaN(numVal)) {
          console.warn('发现NaN值，替换为0:', val)
          return 0
        }
        // 如果值异常（负值或过大），进行限制
        if (numVal < 0) {
          console.warn('发现负值，限制为0:', numVal)
          return 0
        }
        if (numVal > 20000) {
          console.warn('发现过大值，限制为20000:', numVal)
          return 20000
        }
        return numVal
      })
    },
    
    // 获取模型对应颜色
    getModelColor(alpha = 1) {
      const colors = {
        'lightgbm': alpha === 1 ? '#4ecdc4' : `rgba(78, 205, 196, ${alpha})`,
        'xgboost': alpha === 1 ? '#75deef' : `rgba(117, 222, 239, ${alpha})`,
        'ensemble': alpha === 1 ? '#faad14' : `rgba(250, 173, 20, ${alpha})`
      }
      return colors[this.config.model] || (alpha === 1 ? '#75deef' : `rgba(117, 222, 239, ${alpha})`)
    },
    
    // 导出图表数据
    async exportChartData() {
      console.log('🚀 exportChartData方法被调用 - 时间戳:', new Date().toISOString())
      console.log('当前this对象:', this)
      console.log('预测数据长度:', this.predictionData ? this.predictionData.length : 0)
      
      if (!this.predictionData || this.predictionData.length === 0) {
        this.$Message.warning('暂无预测数据可导出')
        return
      }
      
      this.exportLoading = true
      
      try {
        // 生成时间标签
        const timeLabels = []
        for (let i = 0; i < 96; i++) {
          const hour = Math.floor(i / 4)
          const minute = (i % 4) * 15
          const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
          timeLabels.push(timeStr)
        }
        
        // 准备导出数据
        const exportData = {
          export_info: {
            export_time: getUTCTimezoneInfo().currentTime,
            target_date: prepareDateForAPI(this.config.target_date),
            model: this.config.model,
            total_points: this.predictionData.length,
            data_type: 'load_prediction'
          },
          chart_data: timeLabels.map((time, index) => ({
            time_point: time,
            time_index: index + 1,
            predicted_load: this.predictionData[index] || 0,
            timestamp: new Date(prepareDateForAPI(this.config.target_date) + 'T' + time + ':00Z').toISOString()
          })),
          metrics: this.currentMetrics,
          model_config: {
            model: this.config.model,
            target_date: prepareDateForAPI(this.config.target_date),
            granularity: this.config.granularity
          }
        }
        
        // 调用后端导出API
        const response = await predictionAPI.exportChartData(exportData)
        
        console.log('导出API响应:', response)
        console.log('响应数据类型:', typeof response)
        console.log('响应数据结构:', JSON.stringify(response, null, 2))
        
        if (response && response.success) {
          console.log('开始下载文件...')
          // 自动下载文件
          const downloadUrl = response.data.download_url
          console.log('下载URL:', downloadUrl)
          if (downloadUrl) {
            // 使用XMLHttpRequest直接下载文件
            try {
              console.log('开始XMLHttpRequest请求...')
              const xhr = new XMLHttpRequest()
              // 修复URL路径，添加 /api/v1 前缀
              const fullUrl = 'http://localhost:8000/api/v1' + downloadUrl.replace('/api/prediction/', '/prediction/')
              console.log('完整下载URL:', fullUrl)
              xhr.open('GET', fullUrl, true)
              xhr.responseType = 'blob'
              
              xhr.onload = () => {
                if (xhr.status === 200) {
                  console.log('XMLHttpRequest请求成功，开始处理blob...')
                  const blob = xhr.response
                  console.log('blob大小:', blob.size)
                  const url = window.URL.createObjectURL(blob)
                  console.log('创建blob URL:', url)
                  const link = document.createElement('a')
                  link.href = url
                  link.download = response.data.filename
                  console.log('设置下载文件名:', response.data.filename)
                  document.body.appendChild(link)
                  link.click()
                  document.body.removeChild(link)
                  window.URL.revokeObjectURL(url)
                  console.log('文件下载完成')
                  this.$Message.success('图表数据导出成功')
                } else {
                  console.error('下载失败:', xhr.status, xhr.statusText)
                  this.$Message.error('文件下载失败')
                }
              }
              
              xhr.onerror = () => {
                console.error('下载错误:', xhr.status, xhr.statusText)
                this.$Message.error('文件下载失败')
              }
              
              xhr.send()
            } catch (error) {
              console.error('下载错误:', error)
              this.$Message.error('文件下载失败: ' + error.message)
            }
          } else {
            this.$Message.success('图表数据导出成功')
          }
        } else {
          throw new Error(response?.message || '导出失败')
        }
        
      } catch (error) {
        console.error('导出图表数据失败:', error)
        console.error('错误详情:', error.response || error)
        this.$Message.error('导出失败: ' + (error.message || '未知错误'))
      } finally {
        this.exportLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.new-prediction-overview {
  width: 100%;
  background: transparent;
  color: #fff;
  
  // 页面标题
  .page-header {
    text-align: center;
    margin-bottom: 30px;
    
    h1 {
      color: #75deef;
      font-size: 32px;
      font-weight: bold;
      margin-bottom: 10px;
      text-shadow: 0 0 20px rgba(117, 222, 239, 0.5);
    }
    
    p {
      color: #999;
      font-size: 16px;
      margin: 0;
    }
  }
  
  // 顶部工具栏
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 20px;
    background: rgba(7, 19, 50, 0.6);
    border: 1px solid #1a3c58;
    border-radius: 12px;
    backdrop-filter: blur(10px);
    
    .toolbar-left {
      .page-title {
        margin: 0;
        font-size: 20px;
        font-weight: bold;
        color: #75deef;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .subtitle {
        color: #999;
        margin-top: 4px;
        font-size: 14px;
      }
    }
    
    .toolbar-right {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .status-indicator {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .status-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: #ff4d4f;
          
          .online & {
            background: #4ecdc4;
            animation: pulse 2s infinite;
          }
        }
        
        .status-text {
          color: #999;
          font-size: 14px;
        }
      }
      
      // 刷新按钮样式
      :deep(.refresh-btn) {
        background: linear-gradient(45deg, #75deef, #4ecdc4) !important;
        border: none !important;
        color: #fff !important;
        
        &:hover {
          background: linear-gradient(45deg, #5bc0de, #3bb3a6) !important;
          transform: translateY(-1px);
        }
        
        &:active {
          transform: translateY(0);
        }
      }
    }
  }
  
  // 预测工作区
  .prediction-workspace {
    display: grid;
    grid-template-columns: 300px 1fr;
    gap: 20px;
    margin-bottom: 24px;
    align-items: end;
    
    // 配置面板
    .config-panel {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      :deep(.ivu-card) {
        height: 100%;
        display: flex;
        flex-direction: column;
        background: rgba(7, 19, 50, 0.6);
        border: 1px solid #1a3c58;
        border-radius: 12px;
        backdrop-filter: blur(10px);
        
        .ivu-card-head {
          background: rgba(7, 19, 50, 0.3) !important;
          border-bottom: 1px solid #1a3c58 !important;
          
          .ivu-card-head-title {
            color: #75deef !important;
            font-weight: bold;
          }
        }
        
        .ivu-card-body {
          background: transparent;
          flex: 1;
          display: flex;
          flex-direction: column;
        }
      }
      
      h3 {
        color: #75deef;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
        text-align: center;
      }
      
      .config-form {
        flex: 1;
        display: flex;
        flex-direction: column;
        
        .form-row {
          margin-bottom: 16px;
          
          .form-label {
            display: block;
            margin-bottom: 8px;
            color: #999;
            font-weight: 500;
          }
          
          // iView组件样式覆盖
          :deep(.ivu-select),
          :deep(.ivu-date-picker) {
            width: 100%;
            
            .ivu-select-selection,
            .ivu-input {
              background: rgba(7, 19, 50, 0.5) !important;
              border-color: #1a3c58 !important;
              color: #fff !important;
              height: 40px;
              
              &:hover {
                border-color: #75deef !important;
              }
              
              &:focus {
                border-color: #75deef !important;
                box-shadow: 0 0 0 2px rgba(117, 222, 239, 0.2) !important;
              }
            }
            
            // 选中项的文字显示
            .ivu-select-selected-value {
              color: #4ecdc4 !important;
              font-weight: bold !important;
            }
            
            // 占位符颜色
            .ivu-select-placeholder {
              color: #999 !important;
            }
            
            .ivu-select-arrow {
              color: #999;
            }
          }
          
          :deep(.ivu-radio-group) {
            .ivu-radio-wrapper {
              color: #999;
              
              &:hover {
                color: #75deef;
              }
              
              .ivu-radio-checked {
                .ivu-radio-inner {
                  border-color: #75deef;
                  background-color: #75deef;
                }
              }
            }
          }
        }
        
        .utc-info-section {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 20px;
          color: white;
        }
        
        .utc-time {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;
          font-weight: 500;
        }
        
        .timezone-info {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          opacity: 0.9;
        }
        
        .action-row {
          margin-top: 20px;
          
          :deep(.ivu-btn) {
            height: 40px;
            border-radius: 8px;
            
            &.ivu-btn-primary {
              background: linear-gradient(45deg, #75deef, #4ecdc4);
              border: none;
              color: #fff;
              
              &:hover {
                background: linear-gradient(45deg, #5bc0de, #3bb3a6);
                transform: translateY(-1px);
              }
              
              &:active {
                transform: translateY(0);
              }
            }
          }
        }
      }
      
      // 图表卡片
      .chart-card {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;
        
        :deep(.ivu-card) {
          height: 100%;
          display: flex;
          flex-direction: column;
          
          .ivu-card-body {
            flex: 1;
            display: flex;
            flex-direction: column;
          }
        }
        
        .chart-container {
          flex: 1;
          min-height: 400px !important;
          height: 400px !important;
          width: 100% !important;
          display: block !important;
        }
        
        .chart-placeholder {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #999;
          
          .ivu-icon {
            margin-bottom: 16px;
          }
        }
      }
    }
    
    // 结果面板
    .results-panel {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      // 指标网格
      .metrics-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        margin-bottom: 16px;
        flex-shrink: 0;
        
        .metric-card {
          background: rgba(7, 19, 50, 0.4);
          border: 1px solid #1a3c58;
          border-radius: 12px;
          padding: 20px;
          display: flex;
          align-items: center;
          gap: 16px;
          backdrop-filter: blur(10px);
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(117, 222, 239, 0.2);
          }
          
          .metric-icon {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            
            &.metric-blue { background: rgba(117, 222, 239, 0.2); color: #75deef; }
            &.metric-red { background: rgba(255, 77, 79, 0.2); color: #ff4d4f; }
            &.metric-green { background: rgba(78, 205, 196, 0.2); color: #4ecdc4; }

          }
          
          .metric-content {
            flex: 1;
            
            .metric-value {
              font-size: 20px;
              font-weight: bold;
              color: #fff;
              margin-bottom: 4px;
            }
            
            .metric-label {
              color: #999;
              font-size: 14px;
              margin-bottom: 4px;
            }
            
            .metric-trend {
              font-size: 12px;
              display: flex;
              align-items: center;
              gap: 4px;
              
              &.up { color: #4ecdc4; }
              &.down { color: #ff4d4f; }
            }
          }
        }
      }
      
      // 图表卡片
      .chart-card {
        height: 100%;
        background: rgba(7, 19, 50, 0.6);
        border: 1px solid #1a3c58;
        border-radius: 12px;
        backdrop-filter: blur(10px);
        
        :deep(.ivu-card-head) {
          background: rgba(7, 19, 50, 0.3) !important;
          border-bottom: 1px solid #1a3c58 !important;
          
          .ivu-card-head-title {
            color: #75deef !important;
            font-weight: bold;
          }
        }
        
        :deep(.ivu-card-body) {
          background: transparent;
        }
        
        .chart-controls {
          float: right;
          
          .export-btn {
            background: linear-gradient(45deg, #19be6b, #52c41a) !important;
            border: none !important;
            color: #fff !important;
            
            &:hover {
              background: linear-gradient(45deg, #18a058, #389e0d) !important;
              transform: translateY(-1px);
            }
            
            &:active {
              transform: translateY(0);
            }
          }
        }
        
        .chart-container {
          height: 400px !important;
          width: 100% !important;
          min-height: 400px !important;
          display: block !important;
        }
        
        .chart-placeholder {
          height: 400px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #999;
          
          p {
            margin-top: 16px;
            font-size: 16px;
          }
        }
      }
    }
  }
  
  // 分析区域
  .analysis-section {
    margin-bottom: 24px;
    
    .analysis-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 20px;
      max-width: 1800px;
      margin: 0 auto;
      
      .analysis-card {
        background: rgba(7, 19, 50, 0.6);
        border: 1px solid #1a3c58;
        border-radius: 12px;
        backdrop-filter: blur(10px);
        padding: 30px;
        display: flex;
        flex-direction: column;
        min-height: 400px;
        
        .card-header {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          padding-bottom: 10px;
          border-bottom: 1px solid #1a3c58;
          
          .ivu-icon {
            margin-right: 8px;
            font-size: 16px;
            color: #75deef;
          }
          
          h3 {
            color: #75deef;
            font-size: 15px;
            font-weight: bold;
            margin: 0;
          }
        }
        
        // 特征重要性分析
        .importance-chart {
          height: 350px;
          margin-bottom: 30px;
        }
        
        .importance-insights {
          flex: 1;
          margin-top: 30px;
          
          h4 {
            color: #fff;
            margin-bottom: 12px;
            font-size: 14px;
            font-weight: bold;
          }
          
          .insight-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 12px;
            padding: 12px;
            background: rgba(7, 19, 50, 0.4);
            border-radius: 8px;
            border: 1px solid rgba(26, 60, 88, 0.3);
            
            .ivu-icon {
              margin-right: 6px;
              font-size: 14px;
              margin-top: 1px;
              flex-shrink: 0;
            }
            
            span {
              color: #fff;
              font-size: 12px;
              line-height: 1.3;
            }
          }
        }
        
        // 模型性能指标
        .performance-summary {
          flex: 1;
          
          h4 {
            color: #fff;
            margin-bottom: 12px;
            text-align: center;
            font-size: 14px;
            font-weight: bold;
          }
          
          .performance-factor {
            margin-bottom: 12px;
            padding: 12px;
            background: rgba(7, 19, 50, 0.3);
            border: 1px solid #1a3c58;
            border-radius: 6px;
            backdrop-filter: blur(10px);
            
            .factor-name {
              color: #fff;
              margin-bottom: 6px;
              font-weight: bold;
              font-size: 13px;
            }
            
            .factor-impact {
              font-size: 11px;
              margin-bottom: 10px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              
              &.excellent { color: #52c41a; }
              &.good { color: #faad14; }
              &.normal { color: #ff4d4f; }
              
              .impact-score {
                font-weight: bold;
                font-size: 12px;
              }
            }
            
            // 进度条样式
            :deep(.ivu-progress) {
              .ivu-progress-outer {
                background: rgba(7, 19, 50, 0.5);
                border-radius: 6px;
                height: 6px;
              }
              
              .ivu-progress-inner {
                border-radius: 6px;
                height: 6px;
              }
            }
          }
        }
        
        // 气象影响分析
        .weather-impact-chart {
          height: 320px;
          margin-bottom: 0;
          flex: 1;
        }
      }
    }
  }
  
  // 历史记录
  .history-section {
    background: rgba(7, 19, 50, 0.6);
    border: 1px solid #1a3c58;
    border-radius: 12px;
    backdrop-filter: blur(10px);
    
    :deep(.ivu-card-head) {
      background: rgba(7, 19, 50, 0.3) !important;
      border-bottom: 1px solid #1a3c58 !important;
      color: #75deef;
      
      .ivu-card-head-title {
        color: #75deef !important;
        font-weight: bold;
        
        .history-description {
          color: #75deef;
          font-size: 12px;
          font-weight: normal;
          margin-left: 10px;
          opacity: 0.8;
        }
      }
    }
    
    :deep(.ivu-card-body) {
      background: transparent;
    }
    
    :deep(.ivu-table) {
      background: transparent;
      
      &-thead > tr > th {
        background: rgba(7, 19, 50, 0.6) !important;
        border-color: #1a3c58 !important;
        color: #4ecdc4 !important;
        font-weight: bold;
        font-size: 14px;
        text-align: center;
        padding: 12px 8px !important;
        
        &:first-child {
          border-top-left-radius: 8px;
        }
        
        &:last-child {
          border-top-right-radius: 8px;
        }
        
        // 表头文字发光效果
        text-shadow: 0 0 8px rgba(78, 205, 196, 0.3);
      }
      
      &-tbody > tr > td {
        background: rgba(7, 19, 50, 0.2) !important;
        border-color: #1a3c58 !important;
        color: #999 !important;
        text-align: center;
        padding: 10px 8px !important;
      }
      
      &-tbody > tr:hover > td {
        background: rgba(117, 222, 239, 0.15) !important;
        color: #fff !important;
        transition: all 0.3s ease;
      }
      
      // 表格最后一行圆角
      &-tbody > tr:last-child > td {
        &:first-child {
          border-bottom-left-radius: 8px;
        }
        
        &:last-child {
          border-bottom-right-radius: 8px;
        }
      }
      
      &-wrapper {
        background: transparent;
        border-radius: 8px;
        overflow: hidden;
      }
    }
    
    // 操作按钮样式
    :deep(.ivu-btn-text) {
      color: #4ecdc4;
      
      &:hover {
        color: #75deef;
        background: rgba(117, 222, 239, 0.1);
      }
    }
  }
}

// 动画
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

// 响应式设计
@media (max-width: 1200px) {
  .new-prediction-overview {
    .prediction-workspace {
      grid-template-columns: 1fr;
      
      .results-panel .metrics-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }
    
    .analysis-section {
      .importance-analysis,
      .weather-analysis {
        grid-template-columns: 1fr;
      }
    }
  }
}

@media (max-width: 768px) {
  .new-prediction-overview {
    padding: 10px;
    
    .toolbar {
      flex-direction: column;
      gap: 16px;
      text-align: center;
    }
    
    .results-panel .metrics-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>

<!-- 全局样式修复下拉框 -->
<style lang="less">
// 修复iView下拉框选项的背景和文字颜色
.ivu-select-dropdown {
  background: rgba(7, 19, 50, 0.95) !important;
  border: 1px solid #1a3c58 !important;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3) !important;
  
  .ivu-option {
    background: transparent !important;
    color: #fff !important;
    padding: 8px 16px !important;
    font-size: 14px !important;
    
    &:hover:not(.ivu-option-selected) {
      background: rgba(117, 222, 239, 0.15) !important;
      color: #fff !important;
    }
    
    &.ivu-option-selected {
      background: rgba(78, 205, 196, 0.25) !important;
      color: #4ecdc4 !important;
      font-weight: bold !important;
      
      &:hover {
        background: rgba(78, 205, 196, 0.35) !important;
        color: #4ecdc4 !important;
      }
    }
    
    &.ivu-option-focused:not(.ivu-option-selected) {
      background: rgba(117, 222, 239, 0.15) !important;
      color: #fff !important;
    }
    
    // 确保选项内的图标和文字颜色正确
    .ivu-icon {
      color: inherit !important;
      margin-right: 8px !important;
    }
    
    span {
      color: inherit !important;
    }
    
    // 修复自定义div布局的选项
    div {
      color: inherit !important;
      
      span {
        color: inherit !important;
      }
    }
  }
}

// 特别处理选择框的下拉面板定位
.ivu-select-dropdown.ivu-select-dropdown-placement-bottom {
  background: rgba(7, 19, 50, 0.95) !important;
  border: 1px solid #1a3c58 !important;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}

// 修复选择框聚焦时的样式
.ivu-select-focused .ivu-select-selection {
  border-color: #75deef !important;
  box-shadow: 0 0 0 2px rgba(117, 222, 239, 0.2) !important;
}

// 全局修复选择框的选中值显示
.ivu-select .ivu-select-selection {
  .ivu-select-selected-value {
    color: #4ecdc4 !important;
    font-weight: bold !important;
    font-size: 14px !important;
  }
  
  .ivu-select-placeholder {
    color: #999 !important;
    font-size: 14px !important;
  }
  
  // 修复选择框箭头
  .ivu-select-arrow {
    color: #999 !important;
  }
}

// 全局按钮主题样式
.refresh-btn.ivu-btn-primary {
  background: linear-gradient(45deg, #75deef, #4ecdc4) !important;
  border: none !important;
  color: #fff !important;
  
  &:hover {
    background: linear-gradient(45deg, #5bc0de, #3bb3a6) !important;
    transform: translateY(-1px);
  }
  
  &:active {
    transform: translateY(0);
  }
}

// 图表控制按钮组
.chart-btn-group .ivu-btn {
  background: rgba(7, 19, 50, 0.4) !important;
  border-color: #1a3c58 !important;
  color: #999 !important;
  
  &:hover {
    background: rgba(117, 222, 239, 0.2) !important;
    border-color: #75deef !important;
    color: #fff !important;
  }
  
  &.ivu-btn-primary {
    background: linear-gradient(45deg, #75deef, #4ecdc4) !important;
    border-color: #75deef !important;
    color: #fff !important;
    
    &:hover {
      background: linear-gradient(45deg, #5bc0de, #3bb3a6) !important;
      transform: translateY(-1px);
    }
  }
}

// 全局表格主题样式
.history-section .ivu-table {
  .ivu-table-thead > tr > th {
    background: rgba(7, 19, 50, 0.6) !important;
    border-color: #1a3c58 !important;
    color: #4ecdc4 !important;
    font-weight: bold !important;
    text-shadow: 0 0 8px rgba(78, 205, 196, 0.3) !important;
    text-align: center !important;
  }
  
  .ivu-table-tbody > tr > td {
    background: rgba(7, 19, 50, 0.2) !important;
    border-color: #1a3c58 !important;
    color: #999 !important;
    text-align: center !important;
  }
  
  .ivu-table-tbody > tr:hover > td {
    background: rgba(117, 222, 239, 0.15) !important;
    color: #fff !important;
  }
}

// 日期选择器面板
.ivu-date-picker-dropdown {
  background: rgba(7, 19, 50, 0.95) !important;
  border: 1px solid #1a3c58 !important;
  backdrop-filter: blur(10px);
  
  .ivu-picker-panel-content {
    background: transparent !important;
    
    .ivu-date-picker-header {
      border-bottom: 1px solid #1a3c58 !important;
      
      .ivu-date-picker-header-label {
        color: #75deef !important;
        
        &:hover {
          color: #4ecdc4 !important;
        }
      }
    }
    
    .ivu-date-picker-cells {
      .ivu-date-picker-cells-cell {
        color: #999 !important;
        
        &:hover {
          background: rgba(117, 222, 239, 0.2) !important;
          color: #fff !important;
        }
        
        &.ivu-date-picker-cells-cell-selected {
          background: #75deef !important;
          color: #fff !important;
        }
        
        &.ivu-date-picker-cells-cell-today {
          color: #4ecdc4 !important;
        }
      }
    }
  }
}

// 特征重要性图表容器
.importance-charts {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 16px;
  
  .feature-importance-comparison,
  .model-weight-category-chart {
    background: rgba(7, 19, 50, 0.3);
    border: 1px solid #1a3c58;
    border-radius: 8px;
    padding: 16px;
    backdrop-filter: blur(10px);
    
    .chart-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      
      h4 {
        color: #4ecdc4;
        font-weight: bold;
        margin: 0;
        display: flex;
        align-items: center;
        
        .ivu-icon {
          margin-right: 8px;
        }
      }
      
      .chart-controls {
        display: flex;
        gap: 10px;
        align-items: center;
      }
    }
    
    .chart-container {
      min-height: 300px;
      position: relative;
    }
    
    .chart-content {
      width: 100%;
      height: 100%;
      min-height: 300px;
    }
  }
}

// 气象信息样式
.weather-info-section {
  margin-top: 16px;
  padding: 10px;
  background: rgba(7, 19, 50, 0.3);
  border: 1px solid #1a3c58;
  border-radius: 8px;
  backdrop-filter: blur(10px);
  flex: 1;
  overflow-y: auto;
  
  .weather-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    color: #4ecdc4;
    font-weight: bold;
    font-size: 13px;
    
    .ivu-icon {
      margin-right: 6px;
      font-size: 14px;
    }
  }
  
  .weather-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 6px;
    min-height: 0;
    
    .weather-item {
      display: flex;
      align-items: center;
      padding: 6px;
      background: rgba(7, 19, 50, 0.4);
      border: 1px solid #1a3c58;
      border-radius: 6px;
      transition: all 0.3s ease;
      
      &:hover {
        background: rgba(117, 222, 239, 0.1);
        border-color: #75deef;
        transform: translateY(-1px);
      }
      
      .weather-icon {
        margin-right: 8px;
        
        .ivu-icon {
          font-size: 16px;
        }
      }
      
      .weather-content {
        flex: 1;
        
        .weather-value {
          font-size: 13px;
          font-weight: bold;
          color: #fff;
          margin-bottom: 1px;
        }
        
        .weather-label {
          font-size: 10px;
          color: #999;
        }
      }
    }
  }
}
</style>